<template>
  <div class="login-container">
    <van-nav-bar
      title="登录"
      left-arrow
      @click-left="$router.back()"
    />
    <van-form @submit="onSubmit">
      <van-field
        v-model="mobile"
        required
        name="mobile"
        label="手机号"
        :error="false"
        placeholder="请输入手机号"
        :rules="[{ required: true, message: '手机号不能为空' },
                 {pattern:/^[1](([3][0-9])|([4][5-9])|([5][0-3,5-9])|([6][5,6])|([7][0-8])|([8][0-9])|([9][1,8,9]))[0-9]{8}$/,message:'请输入正确的手机号'} ]"
      />
      <van-field
        v-model="code"
        required
        type="password"
        name="code"
        label="验证码"
        :error="false"
        placeholder="请输入验证码"
        :rules="[{ required: true, message: '验证码不能为空' },{validator:codeValidator,message:'请输入正确的验证码'}]"
      />
      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit">登录</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { login } from '@/api/user'
import { mapMutations } from 'vuex'

export default {
  name: 'Login',
  data() {
    return {
      mobile: '',
      code: ''
    }
  },
  methods: {
    ...mapMutations('user', ['changeToken']),
    async onSubmit(values) {
      try {
        this.$toast.loading({
          duration: 0,
          message: '加载中...',
          overlay: true,
          forbidClick: true
        })
        const res = await login(values)
        this.changeToken(res.data)
        // 一个页面上只有一个toast, 它会把上面的Loading状态覆盖掉
        this.$toast.success({ message: '登陆成功', closeOnClick: true })
        // 1. 回到登录前客户要去的页面 如果没有就跳转首页
        this.$router.push(this.$route.query.prevPath || '/')

        // 2. 如果有目标地址就回退(退到客户点击之前的页面) 如果没有就跳转首页
        // this.$route.query.prevPath && this.$router.back()
        // this.$router.push('/')
      } catch (error) {
        console.log(error)
        this.$toast.fail({ message: '登陆失败', closeOnClick: true })
      }
    },
    codeValidator(val) {
      if (val.length === 6) {
        return true
      } else {
        return false
      }
    }
  }
}
</script>

<style></style>
